import webpack, { Configuration } from 'webpack';
import middleware from 'webpack-dev-middleware';
import express from 'express';
import merge from 'webpack-merge';
import { createProxyMiddleware } from 'http-proxy-middleware';
import WebpackHotMiddleware from 'webpack-hot-middleware';
import webpackBaseConfig from '../build/webpack.base.config';
import webpackDevConfig from '../build/webpack.dev.config';
import devServerConfig from '../config/dev.config';

const app = express();
const mergeConfig: Configuration = merge(webpackBaseConfig, webpackDevConfig);

const compiler = webpack(mergeConfig);
const getConfig = (): middleware.Options => {
  const configKey = ['methods'];
  const config: middleware.Options = {};
  for (let k of configKey) {
    //@ts-ignore
    if (devServerConfig[k]) config[k] = devServerConfig[k];
  }
  config.publicPath = '/';
  return config;
};

// 解决刷新404
app.use((req, res, next) => {
  if (/text\/html/.test(req.headers.accept as string)) {
    req.url = '/'; // this would make express-js serve index.html
  }
  next();
});

app.use(middleware(compiler, getConfig()));
app.use(
  //@ts-ignore
  WebpackHotMiddleware(compiler, {
    log: console.log,
    path: '/__webpack_hmr',
    heartbeat: 10 * 1000,
  })
);

console.log(process.argv[2]);

app.use(
  '/api',
  createProxyMiddleware({
    target: `${
      process.argv[2] === 'dev'
        ? 'http://112.124.66.30:3000/v1'
        : 'http://localhost:3000/v1'
    }`,
    pathRewrite: {
      '^/api': '',
    },
    changeOrigin: true,
    logLevel: 'silent',
  })
);



app.listen(devServerConfig.port);
